package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.*;
import com.tanhua.common.pojo.*;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.server.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class TestSoulService {

    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private QuestionnaireReportMapper questionnaireReportMapper;

    @Autowired
    private QuestionnaireResultMapper questionnaireResultMapper;

    @Autowired
    private QuestionUserLockMapper questionUserLockMapper;

    @Autowired
    private SoulQuestionMapper soulQuestionMapper;

    @Autowired
    private SoulQuestionOptionMapper soulQuestionOptionMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private SoulSimilarYouMapper soulSimilarYouMapper;

    @Autowired
    private UserInfoService userInfoService;


    public List<QuestionnaireVo> QuestionnaireLike() {
        //拿到用户id
        User user = UserThreadLocal.get();
        //要返回的问卷对象(包括低中高三个问卷)


        List<QuestionnaireVo> questionnaireVoList = new ArrayList<>();
        //通过user_Id找到QuestionUserLock表中的user_id拿到问卷id和锁状态存到问卷vo里面
        QueryWrapper<QuestionUserLock> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("user_id", user.getId());
        //去题库锁中,查找该用户题库解锁的情况(低中高)
        List<QuestionUserLock> questionUserLock = this.questionUserLockMapper.selectList(queryWrapper1);
        for (QuestionUserLock questionUserLocks : questionUserLock) {
            QuestionnaireVo questionnaireVo = new QuestionnaireVo();
            //问卷编号
            questionnaireVo.setId(String.valueOf(questionUserLocks.getQuestionnaireId()));
            //问卷解锁的状态
            questionnaireVo.setIsLock(questionUserLocks.getIsLock());
            //添加到返回的List对象中
            questionnaireVoList.add(questionnaireVo);
        }

        //拿出问卷Id的集合  123
        List<Long> questionnaireId = new ArrayList();
        for (QuestionUserLock lock : questionUserLock) {
            questionnaireId.add(lock.getQuestionnaireId());

        }

        //通过拿到的问卷id找到问题表中的数据存在返回问卷vo中
        QueryWrapper<Questionnaire> queryLockList = new QueryWrapper<>();
        queryLockList.in("id", questionnaireId);//123
        List<Questionnaire> soulQuestionnaire = this.questionnaireMapper.selectList(queryLockList);
        for (Questionnaire questionnaire : soulQuestionnaire) {//123
            for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
                //把返回vo中的id与从问题表中拿到的id进行对比,确定存放的是同一个vo返回对象
                if (questionnaire.getId().toString().equals(questionnaireVo.getId().toString())) {
                    //卷子 补全信息
                    questionnaireVo.setLevel(questionnaire.getLevel().name());
                    questionnaireVo.setName(questionnaire.getName());
                    questionnaireVo.setCover(questionnaire.getCover());
                    questionnaireVo.setStar(questionnaire.getStar());
                }
            }
        }
        List<SoulQuestionVo> soulQuestionVos1 = new ArrayList<>();
        List<SoulQuestionVo> soulQuestionVos2 = new ArrayList<>();
        List<SoulQuestionVo> soulQuestionVos3 = new ArrayList<>();
        //把问题vo填充到问卷vo中
        for (QuestionnaireVo questionnaireVo : questionnaireVoList) {
            //拿到试题数据
            QueryWrapper<SoulQuestion> queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("questionnaire_id", questionnaireId);//123
            //List<SoulQuestionVo> questions;字段中还缺少SoulQuestionVo集合
            //从数据库中拿到SoulQuestionVo信息
            //通过问卷等级  查询相应的题目等级list
            List<SoulQuestion> soulQuestions = this.soulQuestionMapper.selectList(queryWrapper3);//拿到了某个等级的所有题目集合
            List<SoulQuestionVo> soulQuestionVos = new ArrayList<>();
            //填充SoulQuestionVo的数据
            for (SoulQuestion soulQuestion : soulQuestions) {
                //补全问卷的题目
                SoulQuestionVo soulQuestionVo = new SoulQuestionVo();
                //题目id
                soulQuestionVo.setId(String.valueOf(soulQuestion.getId()));
                //题目 的问题
                soulQuestionVo.setQuestion(soulQuestion.getStem());
                //题目难度
                soulQuestionVo.setLevel(Convert.toInt(soulQuestion.getQuestionnaireId()));

                //所有问题信息补全完(题目编号 和 题目问题内容)
                soulQuestionVos.add(soulQuestionVo);

                //SoulQuestionVo中还有一个List<SoulQuestionOptionVo> options-----选项集合没有填充
                QueryWrapper<SoulQuestionOption> queryWrapper4 = new QueryWrapper<>();
                queryWrapper4.in("question_id", soulQuestion.getId());
                List<SoulQuestionOption> soulQuestionList = this.soulQuestionOptionMapper.selectList(queryWrapper4);
                List<SoulQuestionOptionVo> soulQuestionOptionVo = new ArrayList<>();
                //填充soulQuestionOptionVo1数据
                for (SoulQuestionOption option : soulQuestionList) {
                    SoulQuestionOptionVo soulQuestionOptionVo1 = new SoulQuestionOptionVo();
                    soulQuestionOptionVo1.setId(String.valueOf(option.getId()));
                    soulQuestionOptionVo1.setOption(option.getContent());
                    soulQuestionOptionVo.add(soulQuestionOptionVo1);
                }
                //把选项vo集合填充到问题对象中
                soulQuestionVo.setOptions(soulQuestionOptionVo);
                //把问题对象填充到返回问卷vo对象
                if (soulQuestionVo.getLevel() == 1) {
                    if (soulQuestionVos1.size() < 10) {
                        soulQuestionVos1.add(soulQuestionVo);
                    }
                }
                if (soulQuestionVo.getLevel() == 2) {
                    if (soulQuestionVos2.size() < 10) {
                        soulQuestionVos2.add(soulQuestionVo);
                    }

                }
                if (soulQuestionVo.getLevel() == 3) {
                    if (soulQuestionVos3.size() < 10) {
                        soulQuestionVos3.add(soulQuestionVo);
                    }
                }
            }
            if (questionnaireVo.getId().equals("1")) {

                questionnaireVo.setQuestions(soulQuestionVos1);
            }
            if (questionnaireVo.getId().equals("2")) {
                questionnaireVo.setQuestions(soulQuestionVos2);
            }
            if (questionnaireVo.getId().equals("3")) {
                questionnaireVo.setQuestions(soulQuestionVos3);
            }
        }

        return questionnaireVoList;
    }

    /**
     * 测灵魂题目提交
     *
     * @param answersList
     */
    public String testSoul(List<Answers> answersList) {
        Integer score = 0;
        Long questionId = 0L;
        int wai = 0;
        int juge = 0;
        int abs = 0;
        int lixin = 0;

        //计算分数
        for (Answers answers : answersList) {
            questionId = answers.getQuestionId();
            Long optionId = answers.getOptionId();
            QueryWrapper queryWrapper = new QueryWrapper();
            //queryWrapper.eq("question_id", questionId);
            queryWrapper.eq("id", optionId);
            SoulQuestionOption soulQuestionOption = soulQuestionOptionMapper.selectOne(queryWrapper);
            score += Integer.parseInt(soulQuestionOption.getScore());

            Integer type = soulQuestionOption.getType();
            switch (type) {
                case 1:
                    wai++;
                    break;
                case 2:
                    juge++;
                    break;
                case 3:
                    abs++;
                    break;
                case 4:
                    lixin++;
                    break;
                default:
                    break;
            }
        }

        //.将得分存到

        //通过题目id查到对应的问卷id
        SoulQuestion soulQuestion = soulQuestionMapper.selectById(questionId);
        Long questionnaireId = soulQuestion.getQuestionnaireId();

        //默认初级开启
        QueryWrapper<QuestionUserLock> queryWrapper = new QueryWrapper();
        if (questionnaireId <= 2) {
            queryWrapper.eq("questionnaire_id", questionnaireId + 1);
            queryWrapper.eq("user_id",UserThreadLocal.get().getId());
            QuestionUserLock questionUserLock = questionUserLockMapper.selectOne(queryWrapper);
            if (questionUserLock.getIsLock().equals(1)) {
                questionUserLock.setIsLock(0);
                questionUserLockMapper.update(questionUserLock, queryWrapper);
            }
        }
        //根据问卷id,查看结果表，看总分在哪个区间，判断你的性格，并把数据都添加到报告表里
        QueryWrapper<QuestionnaireResult> query3 = new QueryWrapper<>();
        query3.eq("questionnaire_id", questionnaireId);
        List<QuestionnaireResult> questionnaireResults = questionnaireResultMapper.selectList(query3);

        QuestionnaireReport questionnaireReport = new QuestionnaireReport();
        questionnaireReport.setUserId(UserThreadLocal.get().getId());
        questionnaireReport.setCreated(new Date());

        int count = wai + juge + abs + lixin;
        questionnaireReport.setExtroversion(Long.valueOf(wai));
        questionnaireReport.setJudgement(Long.valueOf(juge));
        questionnaireReport.setAbstraction(Long.valueOf(abs));
        questionnaireReport.setRetionality(Long.valueOf(lixin));

        for (QuestionnaireResult questionnaireResult : questionnaireResults) {
            String[] split = questionnaireResult.getScope().split(",");
            if (score >= Integer.valueOf(split[0]) && score <= Integer.valueOf(split[1])) {
                questionnaireReport.setConclusionId(questionnaireResult.getId());
                break;
            }
        }

        int insert = questionnaireReportMapper.insert(questionnaireReport);

        QuestionnaireReport questionnaireReport1;
        if (insert > 0) {
            QueryWrapper<QuestionnaireReport> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", UserThreadLocal.get().getId()).orderByDesc("created");
            //wrapper.eq("user_id", UserThreadLocal.get().getId());

            questionnaireReport1 = questionnaireReportMapper.selectList(wrapper).get(0);

            //1.创建与你相似表对象
            SoulSimilarYou soulSimilarYou = new SoulSimilarYou();
            soulSimilarYou.setUserId(UserThreadLocal.get().getId());
            soulSimilarYou.setReportId(questionnaireReport1.getId());
            soulSimilarYou.setScore(score);
            soulSimilarYou.setCreated(new Date());

            //保存分数和报告id与用户id
            int result = soulSimilarYouMapper.insert(soulSimilarYou);

            if (result == 0) {
                return null;
            }
            //2.解锁下一级
            QueryWrapper<QuestionUserLock> queryWrapper1 = new QueryWrapper<>();
            queryWrapper1.eq("user_id", UserThreadLocal.get().getId());
            List<QuestionUserLock> questionUserLocks = questionUserLockMapper.selectList(queryWrapper1);
            QuestionUserLock questionUserLock = questionUserLocks.get(1);
            QuestionUserLock questionUserLock1 = questionUserLocks.get(2);
            //3.判断试卷是否锁住
            if (questionUserLock.getIsLock() == 1) {
                QueryWrapper<QuestionUserLock> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("user_id", UserThreadLocal.get().getId());
                questionUserLock.setIsLock(0);
                questionUserLockMapper.update(questionUserLock, queryWrapper2);
            }
            if (questionUserLock1.getIsLock() == 2) {
                QueryWrapper<QuestionUserLock> query2 = new QueryWrapper<>();
                query2.eq("user_id", UserThreadLocal.get().getId());
                questionUserLock1.setIsLock(0);
                questionUserLockMapper.update(questionUserLock1, query2);
            }

            return questionnaireReport1.getId().toString();
        }
        return null;
    }


    /**
     * 灵魂测试结果
     *
     * @param id
     * @return
     */
    public TestResultVo testResult(Long id) {
        Long userId = UserThreadLocal.get().getId();
        //1.创建返回结果对象
        TestResultVo testResultVo = new TestResultVo();

        //2.通过传递的id查询报告表
        QuestionnaireReport questionnaireReport = questionnaireReportMapper.selectById(id);

        //3.通过报告表中的结论id查询结论表
        QuestionnaireResult questionnaireResult = questionnaireResultMapper.selectById(questionnaireReport.getConclusionId());

        //4.填充结论与封面到返回结果中
        testResultVo.setConclusion(questionnaireResult.getContent());
        testResultVo.setCover(questionnaireResult.getCover());

        //5.创建任务性格集合
        List<Dimensions> dimensionsList = new ArrayList<>();

        //6.创建性格
        //6.1.抽象
        Dimensions dimensions1 = new Dimensions();
        dimensions1.setKey("抽象");
        dimensions1.setValue(Convert.toInt(((questionnaireReport.getAbstraction() / 10.0) * 100.0)) + "%");
        dimensionsList.add(dimensions1);

        //6.2.外向
        Dimensions dimensions2 = new Dimensions();
        dimensions2.setKey("外向");
        dimensions2.setValue(Convert.toInt(((questionnaireReport.getExtroversion() / 10.0) * 100.0)) + "%");
        dimensionsList.add(dimensions2);

        //6.3.判断
        Dimensions dimensions3 = new Dimensions();
        dimensions3.setKey("判断");
        dimensions3.setValue(Convert.toInt((((questionnaireReport.getJudgement() / 10.0) * 100.0)) )+ "%");
        dimensionsList.add(dimensions3);

        //6.4.理性
        Dimensions dimensions4 = new Dimensions();
        dimensions4.setKey("理性");
        dimensions4.setValue(Convert.toInt((((questionnaireReport.getRetionality() / 10) * 100)) )+ "%");
        dimensionsList.add(dimensions4);

        //6.5.设置返回的性格键值对集合
        testResultVo.setDimensions(dimensionsList);

        //7.创建与你相似集合
        List<SimilarYou> similarYous = new ArrayList<>();

        //7.创建与你相似集合
        //7.1.先查询自己的得分
        QueryWrapper<SoulSimilarYou> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", UserThreadLocal.get().getId()).orderByDesc("created");

        SoulSimilarYou soulSimilarYou = soulSimilarYouMapper.selectList(queryWrapper).get(0);
        //7.2.获取自己的分数
        int score = soulSimilarYou.getScore();

        //8.再次查找分数相似的人的id
        QueryWrapper<SoulSimilarYou> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.ge("score", score - 5).le("score", score + 5);


        List<SoulSimilarYou> soulSimilarYous = soulSimilarYouMapper.selectList(queryWrapper1);

        List<SoulSimilarYou> soulSimilarYouList = new ArrayList<>();
        for (int i = 0; i < soulSimilarYous.size(); i++) {
            if (ObjectUtil.equals(soulSimilarYous.get(i).getUserId(), userId)) {
                continue;
            }
            soulSimilarYouList.add(soulSimilarYous.get(i));
        }

        if (CollUtil.isEmpty(soulSimilarYouList)) {
            testResultVo.setSimilarYou(null);
        }

        //9.不为空,拿到该集合中所有的用户id
        List<Object> userIds = CollUtil.getFieldValues(soulSimilarYouList, "userId");

        //10.通过id集合查询用户信息(获取id对应的所有用户信息)
        List<UserInfo> userInfoByUsers = userInfoService.findUserInfoByUserIds(userIds);

        //11.查询用户头像
        for (UserInfo userInfoByUser : userInfoByUsers) {
            //11.1.创建与你相似对象
            SimilarYou similarYou1 = new SimilarYou();
            similarYou1.setId(userInfoByUser.getUserId());
            similarYou1.setAvatar(userInfoByUser.getLogo());
            similarYous.add(similarYou1);
        }

        //12.设置到集合中
        testResultVo.setSimilarYou(similarYous);

        //13.返回结果
        return testResultVo;
    }
}
